import { defineEventHandler, readBody, createError } from 'h3';
import { getDbConnection } from '../../utils/db.js';
import { requireUser } from '../../utils/auth.js';

export default defineEventHandler(async (event) => {
  try {
    const { userId } = requireUser(event);

    const { noteId, versionId } = await readBody(event);
    if (!noteId || !versionId) {
      throw createError({ statusCode: 400, statusMessage: 'Note ID and Version ID are required' });
    }

    const db = await getDbConnection();
    
    // 验证笔记是否属于当前用户
    const note = await db.get(
      'SELECT id, name, content FROM notes WHERE id = ? AND user_id = ?',
      [noteId, userId]
    );
    
    if (!note) {
      throw createError({ statusCode: 404, statusMessage: 'Note not found' });
    }
    
    // 获取要恢复的版本内容
    const versionToRestore = await db.get(
      `SELECT name, content, version_number
       FROM note_versions 
       WHERE note_id = ? AND id = ?`,
      [noteId, versionId]
    );

    if (!versionToRestore) {
      throw createError({ statusCode: 404, statusMessage: 'Version not found' });
    }
    
    // 只有当前内容与目标版本不同时才创建新版本
    if (note.name !== versionToRestore.name || note.content !== versionToRestore.content) {
      // 获取下一个版本号
      const lastVersion = await db.get(
        'SELECT MAX(version_number) as last_version FROM note_versions WHERE note_id = ?',
        [noteId]
      );
      
      const nextVersion = (lastVersion?.last_version || 0) + 1;
      
      // 保存当前状态作为新版本
      await db.run(
        `INSERT INTO note_versions (note_id, name, content, version_number, change_summary) 
         VALUES (?, ?, ?, ?, ?)`,
        [noteId, note.name, note.content, nextVersion, `恢复到版本 ${versionToRestore.version_number}`]
      );
    }
    
    // 恢复到指定版本
    await db.run(
      `UPDATE notes 
       SET name = ?, content = ?, updated_at = CURRENT_TIMESTAMP 
       WHERE id = ? AND user_id = ?`,
      [versionToRestore.name, versionToRestore.content, noteId, userId]
    );

    return { 
      success: true, 
      restoredVersion: versionToRestore.version_number,
      message: `已恢复到版本 ${versionToRestore.version_number}` 
    };
  } catch (error) {
    console.error('Error restoring note version:', error);
    throw createError({ statusCode: 500, statusMessage: 'Failed to restore note version' });
  }
});
